package com.aso114.project.mvp.activity.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.GridAdapter;
import com.aso114.project.adapter.HomeRecommendAdapter;
import com.aso114.project.adapter.ZhiNanAdapter;
import com.aso114.project.base.BaseBean;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.BannerBean;
import com.aso114.project.bean.BuyPaperBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.bean.TrueQuestionBean;
import com.aso114.project.bean.UserInfoBean;
import com.aso114.project.commonview.CustomDatePicker;
import com.aso114.project.commonview.MyGridView;
import com.aso114.project.dialog.ExamTimeDialog;
import com.aso114.project.exam.ExpositionTestActivity;
import com.aso114.project.exam.QuestionTestActivity;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.activity.BannerDetaiActivity;
import com.aso114.project.mvp.activity.ChapterContactActivity;
import com.aso114.project.mvp.activity.EeeorExerciseActivity;
import com.aso114.project.mvp.activity.LoginActivity;
import com.aso114.project.mvp.activity.MainActivity;
import com.aso114.project.mvp.activity.MyCollectActivity;
import com.aso114.project.mvp.activity.NeedNoticeDetailActivity;
import com.aso114.project.mvp.activity.PracticeHistoryActivity;
import com.aso114.project.mvp.activity.SatPracticeTestActivity;
import com.aso114.project.mvp.activity.SelectedTopicActivity;
import com.aso114.project.mvp.activity.SelectedTopicPayActivity;
import com.aso114.project.mvp.activity.VipCoreActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SpfUtil;
import com.aso114.project.util.Timeutils;
import com.aso114.project.util.ToastUtils;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.security.PublicKey;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 行测
 */
public class AdministrarAptitudeTestFragment extends BaseFragment implements OnItemClickListener, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, SwipeMenuRecyclerView.LoadMoreListener {
    public static final String HOME_REFRESH = "home" + "refresh";

    @BindView(R.id.home_liatView)
    SwipeMenuRecyclerView homeLiatView;
    Unbinder unbinder;

    ConvenientBanner convenientBanner;
    MyGridView gridview;
    TextView homeDay1, homeDay2, homeDay3;
    @BindView(R.id.home_refresh_layout)
    SwipeRefreshLayout homeRefreshLayout;

    private CustomDatePicker datePicker;
    private String date;
    private int starYear;
    private List<BannerBean> bannerList;
    //章节练习的
//    ChapterContactAdapter chapterContactAdapter;
//    ModuleExamAdapter moduleExamAdapter;
    private HomeRecommendAdapter recycleAdapter;
    Dialog dialog;
    private List<TrueQuestionBean> listBean = new ArrayList<>();

    //定义图标数组
    private int[] imageRes = {
            R.mipmap.home_kd_ic,
            R.mipmap.home_zj_ic,
            R.mipmap.home_zt_ic,
            R.mipmap.home_lx_ic,
            R.mipmap.home_gg_ic,
            R.mipmap.home_ks_ic,
            R.mipmap.home_ct_ic,
            R.mipmap.home_sc_ic};

    //定义图标下方的名称数组
    private String[] name = {
            "考点练习",
            "章节练习",
            "真题模考",
            "练习历史",
            "巩固模考",
            "精选押题",
            "错题练习",
            "收藏题"
    };

    private GridAdapter adapter;
    Intent intent;
    QuestionBean qdata;
    private int pageNo = 1;
    private boolean isRefresh = false;
    //刷新
    int is_vip = 0;//0 不是vip 1 是 vip
    @Override
    protected int getLayoutResourceId() {
        return R.layout.administraraptitudetest;
    }

    @Override
    protected void initView() {
        homeLiatView.setLayoutManager(new LinearLayoutManager(getActivity()));
        View headerView = getLayoutInflater().inflate(R.layout.home_header, null);
        convenientBanner = headerView.findViewById(R.id.convenientBanner);
        gridview = headerView.findViewById(R.id.gridview);
        headerView.findViewById(R.id.currentDate).setOnClickListener(this);
        homeDay1 = headerView.findViewById(R.id.home_day1);
        homeDay2 = headerView.findViewById(R.id.home_day2);
        homeDay3 = headerView.findViewById(R.id.home_day3);
        //章节练习的
//        moduleExamAdapter = new ModuleExamAdapter();
//        moduleExamAdapter.bindToRecyclerView(homeLiatView);
//        moduleExamAdapter.setOnItemChildClickListener(this);
//        moduleExamAdapter.addHeaderView(headerView);
        homeLiatView.addHeaderView(headerView);
        recycleAdapter = new HomeRecommendAdapter(getActivity(), listBean);
        homeLiatView.setAdapter(recycleAdapter);
        homeRefreshLayout.setOnRefreshListener(this);
        // 加载
        homeLiatView.useDefaultLoadMore();
        homeLiatView.setLoadMoreListener(this);
        recycleAdapter.setOnItemClickListener(new HomeRecommendAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int postion) {
                if (Helper.isLogin()) {
                    return;
                }
                CommentModel.getInstant().getBuyPaper(listBean.get(postion).getPaperId(), new CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        BuyPaperBean paperBean = (BuyPaperBean) o;
                        if (paperBean == null) {
                            return;
                        }
                        if (paperBean.getIsLock() == 1) {//已购买
                            View dialogview = LayoutInflater.from(getActivity()).inflate(R.layout.loading_view, null);
                            final Dialog dialog = new Dialog(getActivity(), R.style.dialogStyle);
                            dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            dialog.getWindow().setGravity(Gravity.CENTER);
                            // 设置点击外围解散
                            dialog.setCanceledOnTouchOutside(true);
                            dialog.setCancelable(true);//设置是否可以按退回键取消
                            dialog.show();
                            CommentModel.getInstant().get_question_bank(LoginSP.getInstance().getUserAreaId(), listBean.get(postion).getPaperId(), Constant.adutst, new CallBack() {
                                @Override
                                public void onSuccess(Object o, boolean isSuccess, String msg) {
                                    dialog.cancel();
                                    Helper.gotoLogin(isSuccess);//token失效去重新登陆
                                    QuestionBean qdata = (QuestionBean) o;
                                    Constant.title_tv = "3";
                                    EventBus.getDefault().postSticky(qdata);
                                    Intent intent = new Intent(getActivity(), QuestionTestActivity.class);
                                    intent.putExtra(QuestionTestActivity.IS_EXAM, true);
                                    getActivity().startActivity(intent);

                                }

                                @Override
                                public void onFailure(String fail) {
                                    Helper.showToast("获取题库失败");
                                    dialog.cancel();
                                }
                            });

                        } else {//未购买
                            Constant.title_tv = "5";
                            intent = new Intent(getContext(), SelectedTopicPayActivity.class);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onFailure(String fail) {

                    }
                });
            }
        });
        getData();
        getListData();
        getType();
    }


//    @Override
//    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//        if (Helper.isLogin()) {
//            return;
//        }
//        final View dialogview = getActivity().getLayoutInflater().inflate(R.layout.loading_view, null);
//        dialog = new Dialog(getContext(), R.style.dialogStyle);
//        dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
//                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//        dialog.getWindow().setGravity(Gravity.CENTER);
//        // 设置点击外围解散
//        dialog.setCanceledOnTouchOutside(true);
//        dialog.setCancelable(true);//设置是否可以按退回键取消
//        dialog.show();
//        // 点击章节练习  进入练习试卷
//        ModuleExamBean moduleExamBean = (ModuleExamBean) adapter.getData().get(position);
//        CommentModel.getInstant().get_chapter_bank(LoginSP.getInstance().getUserAreaId(), moduleExamBean.getSpecialId(), new CallBack() {
//            @Override
//            public void onSuccess(Object o, boolean isSuccess, String msg) {
//                dialog.cancel();
//                Helper.gotoLogin(isSuccess);//token失效去重新登陆
//                qdata = (QuestionBean) o;
//                EventBus.getDefault().postSticky(qdata);
//                Constant.title_tv = "2";
//                intent = new Intent(getContext(), QuestionTestActivity.class);
//                intent.putExtra("is_exam", false);
//                intent.putExtra("isAnalysis", true);
//                startActivity(intent);
//            }
//
//            @Override
//            public void onFailure(String fail) {
//                ToastUtils.showToast(getContext(), "获取题库失败");
//                dialog.cancel();
//            }
//        });
//    }

    private void getData() {
        CommentModel.getInstant().getAptiudeTest_banner(Constant.adutst, "1", new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                bannerList = (List<BannerBean>) o;

                System.out.println("banner数组大小===" + bannerList.size());

                initBanner();

            }

            @Override
            public void onFailure(String fail) {
                bannerList = new ArrayList<>();
                BannerBean bn = new BannerBean();

                bn.setLitpic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543408736304&di=a4bfe0ca275ca305834a525c18cd231d&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181120%2F9c4edc6604e84eba863c75f2e6cd7221.jpeg");
                bannerList.add(bn);
                BannerBean bn1 = new BannerBean();
                bn1.setLitpic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543408563496&di=cbef8feab19013ac5f3b9507a62f75f7&imgtype=0&src=http%3A%2F%2Fd.ifengimg.com%2Fw600%2Fp0.ifengimg.com%2Fpmop%2F2018%2F1105%2F061500E3A7CFE1AA91524E97BEFE84D6A09FE7B7_size98_w1000_h562.jpeg");
                bannerList.add(bn1);

                System.out.println("banner数组大小===" + bannerList.size());
                initBanner();
            }
        });
        // 章节联系的
//        CommentModel.getInstant().getModuleExamList(Constant.adutst, new CallBack<List<ModuleExamBean>>() {
//            @Override
//            public void onSuccess(List<ModuleExamBean> moduleExamBeans, boolean isSuccess, String msg) {
//                //token失效去重新登陆
//                Helper.gotoLogin(isSuccess);
//                if (moduleExamBeans == null || moduleExamBeans.size() == 0) {
//                    return;
//                } else {
//                    ArrayList<MultiItemEntity> res = new ArrayList<MultiItemEntity>(moduleExamBeans);
//                    moduleExamAdapter.setNewData(res);
//                }
//            }
//
//            @Override
//            public void onFailure(String fail) {
//            }
//        });

    }

    private void getListData() {
        CommentModel.getInstant().getRecommend(pageNo, new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                //token失效去重新登陆
                BaseBean<List<TrueQuestionBean>> bean = (BaseBean<List<TrueQuestionBean>>) o;
                Helper.gotoLogin(isSuccess);
                if (homeRefreshLayout == null) {
                    return;
                }
                if (pageNo==1) {
                    listBean.clear();
                    homeRefreshLayout.setRefreshing(false);
                }
                if (bean.getData() == null || bean.getData().size() == 0) {
                    homeLiatView.loadMoreFinish(true, true);
                    recycleAdapter.notifyDataSetChanged();
                } else {
                    if (bean.getData().size() < bean.getPageinfo().getPagesize()) {
                        homeLiatView.loadMoreFinish(true, true);
                    } else {
                        homeLiatView.loadMoreFinish(false, true);
                    }
                    listBean.addAll(bean.getData());
                    recycleAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(String fail) {

            }
        });
    }

    private void initBanner() {
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, bannerList);
        convenientBanner.setPointViewVisible(true)//设置指示器是否可见
                //设置自动切换（同时设置了切换时间间隔）
                .startTurning(3000)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ej_sjkbai_ic, R.mipmap.ej_sjk_ic})
                //设置指示器的方向（左、中、右）
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                //设置点击监听事件
                .setOnItemClickListener(this)
                //设置手动影响（设置了该项无法手动切换）
                .setManualPageable(true);
        if (bannerList.size() > 1) {
            convenientBanner.setCanLoop(true);
            convenientBanner.setPointViewVisible(true);
        } else {
            convenientBanner.setCanLoop(false);
            convenientBanner.setPointViewVisible(false);
        }
    }

    /**
     * banner item点击事件
     */
    @Override
    public void onItemClick(int position) {
        // 获取banner  type
        int type = Integer.valueOf(bannerList.get(position).getLinktype());

        switch (type) {
            case 0:// 无跳转
                break;
            case 1:// 链接
                intent = new Intent(getActivity(), BannerDetaiActivity.class);
                intent.putExtra("linkUrl", bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;
            case 2:// 题库
                if (Helper.isLogin()) {
                    return;
                }
                final String[] id = bannerList.get(position).getLinkurl().split(",");//[考题ID，行测或申论ID，考区ID]
                View dialogview = getActivity().getLayoutInflater().inflate(
                        R.layout.loading_view, null);
                dialog = new Dialog(getActivity(), R.style.dialogStyle);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                dialog.getWindow().setGravity(Gravity.CENTER);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);//设置是否可以按退回键取消
                dialog.show();
                Constant.title_tv = "3";
                CommentModel.getInstant().get_question_bank(id[2], id[0], id[1], new CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                        dialog.cancel();
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        QuestionBean qdata = (QuestionBean) o;

                        EventBus.getDefault().postSticky(qdata);
                        if (Constant.adutst.equals(id[1])) {//行测
                            //行测
                            intent = new Intent(getActivity(), QuestionTestActivity.class);
                            intent.putExtra(QuestionTestActivity.IS_EXAM, true);

                        }
                        if (Constant.essay.equals(id[1])) {//申论
                            //申论
                            intent = new Intent(getActivity(), ExpositionTestActivity.class);

                        }
                        startActivity(intent);

                    }

                    @Override
                    public void onFailure(String fail) {
                        Helper.showToast("获取题库失败");
                        dialog.cancel();
                    }
                });
                break;
            case 3:// 页面（须知）
                intent = new Intent(getContext(), NeedNoticeDetailActivity.class);
                intent.putExtra("type", bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;

            case 4:// 跳转到精题库
                Constant.title_tv = "12";
                intent = new Intent(getContext(), SelectedTopicPayActivity.class);
//                intent.putExtra("type", bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.currentDate:
//                datePicker.show(date);
                // 距离考试还有多少天
                String endTime = SpfUtil.getInstance().getString("dayTime", "2018-01-01");
                ExamTimeDialog dialog = new ExamTimeDialog(getActivity(), dayNum(endTime), endTime, new ExamTimeDialog.OnDialogClick() {
                    @Override
                    public void goBuy() {
                        Constant.title_tv = "5";
                        intent = new Intent(getContext(), SelectedTopicPayActivity.class);
                        startActivity(intent);
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    public void onRefresh() {
        // 下拉刷新
        pageNo = 1;
        homeRefreshLayout.setRefreshing(true);
        getListData();
    }

    @Override
    public void onLoadMore() {
        // 上拉加载
        pageNo++;
        getListData();
    }

    public class NetworkImageHolderView implements Holder<BannerBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, BannerBean data) {
            Glide.with(getActivity()).load(data.getLitpic()).into(imageView);
        }

    }

    /**
     * gridview  的  adapter
     */
    private void getType() {
        adapter = new GridAdapter(imageRes, name);
        gridview.setAdapter(adapter);
        //添加消息处理
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }

                    Constant.title_tv = "1";
                    View dialogview = getActivity().getLayoutInflater().inflate(
                            R.layout.loading_view, null);
                    dialog = new Dialog(getActivity(), R.style.dialogStyle);
                    dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    dialog.getWindow().setGravity(Gravity.CENTER);
                    // 设置点击外围解散
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.setCancelable(true);//设置是否可以按退回键取消
                    dialog.show();

                    CommentModel.getInstant().get_testing_bank(LoginSP.getInstance().getUserAreaId(), Constant.adutst, new CallBack() {
                        @Override
                        public void onSuccess(Object o, boolean isSuccess, String msg) {

                            dialog.cancel();
                            Helper.gotoLogin(isSuccess);//token失效去重新登陆
                            qdata = (QuestionBean) o;

                            EventBus.getDefault().postSticky(qdata);

                            intent = new Intent(getActivity(), QuestionTestActivity.class);
                            intent.putExtra("is_exam", false);
                            intent.putExtra("isAnalysis", true);

                            startActivity(intent);

                        }

                        @Override
                        public void onFailure(String fail) {
                            ToastUtils.showToast(getActivity(), "获取题库失败");
                            dialog.cancel();
                        }
                    });


                }


                if (position == 1) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "2";
                    startActivity(new Intent(getContext(), ChapterContactActivity.class));
                }
                if (position == 2) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "3";
                    //真题模考
                    intent = new Intent(getContext(), SatPracticeTestActivity.class);
                    intent.putExtra("type", "1");
                    intent.putExtra("catid", Constant.adutst);
                    startActivity(intent);
                }
                if (position == 3) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "6";
                    // 练习历史
                    intent = new Intent(getContext(), PracticeHistoryActivity.class);
                    intent.putExtra("catid", Constant.adutst);
                    startActivity(intent);
                }
                if (position == 4) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "4";
                    //巩固模考
                    intent = new Intent(getContext(), SatPracticeTestActivity.class);
                    intent.putExtra("type", "30");
                    startActivity(intent);
                }
                if (position == 5) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    // 精选押题
                    Constant.title_tv = "12";
                    intent = new Intent(getContext(), VipCoreActivity.class);//AboutUsActivity ShowActivity
                    if(is_vip==1){
                        intent.putExtra("vipTpye","1");
                        startActivity(intent);

                    }else{
                        intent.putExtra("vipTpye","0");
                        startActivity(intent);
                    }
//                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
//                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
//                        intent = new Intent(getContext(), LoginActivity.class);
//                        startActivity(intent);
//                        return;
//                    }
//                    Constant.title_tv = "5";
//                    //考试成绩
//                    intent = new Intent(getContext(), ExamResultsActivity.class);
//                    intent.putExtra("type", "30");
//                    startActivity(intent);
                }

                if (position == 6) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "7";
                    //错题练习
                    intent = new Intent(getContext(), EeeorExerciseActivity.class);
//                    intent.putExtra("type", "30");
                    startActivity(intent);
                }
                if (position == 7) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(), "您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "8";
                    //收藏题
                    intent = new Intent(getContext(), MyCollectActivity.class);//
                    intent.putExtra("type", "30");
                    startActivity(intent);
                }


            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();

        if (!TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
            CommentModel.getInstant().getUserInfo(new CallBack() {
                @Override
                public void onSuccess(Object o, boolean isSuccess, String msg) {
                    Helper.gotoLogin(isSuccess);//token失效去重新登陆
                    UserInfoBean loginBean = (UserInfoBean) o;
                    if (loginBean == null) {
                        return;
                    }

                    if (!TextUtils.isEmpty(loginBean.getIsVip())) {
//                        collectnumber.setText(loginBean.getCollectCount());
                        is_vip = Integer.valueOf(loginBean.getIsVip());
                    }
                    SpfUtil.getInstance().putString("dayTime", Helper.getCurrentTime(Long.valueOf(loginBean.getExamTime())));
                    initPicker();
                }

                @Override
                public void onFailure(String fail) {
                    ToastUtils.showToast(getContext(), fail);
                }
            });
        }
        addAction(HOME_REFRESH);
        if (isRefresh){
            pageNo = 1;
            getListData();
        }
    }

    private void initPicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        date = sdf.format(new Date());
        starYear = Integer.valueOf(date.split("-")[0]);
        //设置当前显示的日期
//        currentDate.setText(date);
        String endTime = SpfUtil.getInstance().getString("dayTime", "2018-01-01");
        dayNum(endTime);

        /**
         * 设置年月日
         */
        /**
         * 设置年月日
         */
        datePicker = new CustomDatePicker(getActivity(), "考试时间", new CustomDatePicker
                .ResultHandler() {
            @Override
            public void handle(String time) throws ParseException {
                dayNum(time.split(" ")[0]);
                SpfUtil.getInstance().putString("dayTime", time.split(" ")[0]);
            }

        }, starYear + "-01-01 00:00", (starYear + 2) + "-12-31 23:59");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(true);


    }

    private String dayNum(String time) {
        long starTime = Timeutils.getStringToDate(date, "yyyy-MM-dd");
        long endTime = Timeutils.getStringToDate(time, "yyyy-MM-dd");
        long dayTime = endTime - starTime;
        long day = dayTime / (24 * 60 * 60 * 1000);
        if (day < 0) {
            day = 0;
        }
        String daystr = String.format("%03d", day);
        homeDay1.setText(daystr.substring(0, 1));
        homeDay2.setText(daystr.substring(1, 2));
        homeDay3.setText(daystr.substring(2));
        return daystr;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addOnClick() {

    }

    /**
     * @param action 广播action
     */
    public void addAction(String action) {
        filter = new IntentFilter(action);
        getActivity().registerReceiver(mBroadcastReceiver, filter);
    }


    /**
     * 广播
     */
    public BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            getBroadcast(context, intent);
        }
    };

    /**
     * @param context 获取广播
     * @param intent  获取广播数据
     */
    protected void getBroadcast(Context context, Intent intent) {
        isRefresh = true;
    }

}